<?php


namespace app\api\model;

use app\api\service\Bank;
use app\common\exception\BaseException;
use app\common\model\UserCcard as userCcardmodel;
use app\common\service\Order as OrderService;

class UserCcard extends userCcardmodel
{
    /**
     * 绑定银行卡
     * @param array $data
     */
    public function  bindcard(array $data){
        if (static::where(['certno'=>$data['idno']])->find()){
            throw new BaseException(['msg' => '该银行卡已被绑定过']);
        }
        $data['orderNo'] = OrderService::createOrderNo();
        $data['wxapp_id'] = self::$wxapp_id;
        $this->startTrans();
        try {
            //新增相关数据
            $save_data = [
                'user_id'=>$data['user_id'],
                'orderno'=>$data['orderNo'],
                'realname'=>$data['name'],
                'certno'=>$data['idno'],
                'bankname'=>$data['bankname'],
                'accno'=>$data['acctid'],
                'phoneno'=>$data['mobile'],
                'cvv2'=>$data['cvv2'],
                'validity'=>$data['validity'],
                'status'=>1,
                'wxapp_id'=> $data['wxapp_id']
            ];
            $this->save($save_data);
            $data['ccard_id'] = $this->ccard_id;
            $bank = new Bank();
            $bank->bindcard($data);
            $this->commit();
        }catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return true;
    }

    /**
     * 解绑银行卡
     * @param array $data
     */
    public function unbindcard(array $data){
        if (!$ccardmodel = static ::find($data['ccard_id'])){
            throw new BaseException(['msg' => '找不到对应数据']);
        }
        $data['acctid'] = $ccardmodel->accno;
        $this->startTrans();
        try {
            $bank = new Bank();
            if($bank->unbindcard($data)){
                //删除数据
                static ::where(['ccard_id'=>$data['ccard_id'],'user_id'=>$data['user_id']])->delete();
            }
            $this->commit();
        }catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return true;
    }

    /**
     * 获取用户绑定信用卡号
     * @param $user_id  用户编号
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList($user_id){
        return $this->where(['user_id'=>$user_id])->select();
    }

    /**
     * 获取用户对应绑定信用卡
     * @param $ccard_id
     */
    public function getcards($ccard_id,$user_id){
        if (!$ccard_id){
            throw new BaseException(['msg' => '缺少信用卡参数']);
        }
        return $this->where(['ccard_id'=>$ccard_id,'user_id'=>$user_id])->find();
    }
}